<template>
	<view>
		<view class="content">
			<image class="title_bg" src="../../static/bg_05.png"></image>
			<view class="title_text">
				房间号：{{gameInfo.roomId}}
				总人数：{{gameInfo.gameNum.total}}
			</view>
		</view>
		<view class="content uni-list camp-select" v-show="gameInfo.gameNum.blue == 0">
			<view class="uni-list-cell">
				<view class="uni-list-cell-left">
					请选择红蓝对战人数比
				</view>
				<view class="uni-list-cell-db">
					<picker @change="bindPickerChange" style="text-align: center;" :value="index" :range="array">
						<view class="uni-input">{{array[index]}}</view>
					</picker>
				</view>
			</view>
		</view>

		<view class="content camp-select" v-if="gameInfo.gameNum.blue != 0 && !isCamp && gameInfo.status != 3">
			<view>请选阵营和角色：</view>
			<radio-group @change="handleChange">
				<label class="radio">
					<radio value="1" :checked="camp==1" />
					蓝方剩余位置{{gameInfo.gameNum.blue - gameInfo.blueUsers.length}}个
				</label>
				<br />
				<label class="radio">
					<radio value="2" :checked="camp==2" />
					红方剩余位置{{gameInfo.gameNum.red - gameInfo.redUsers.length}}个
				</label>
			</radio-group>
		</view>

		<view class="content message-padding" v-show="isCamp && gameInfo.status == 1">
			等待{{gameInfo.gameNum.total - gameInfo.curNum.total}}个玩家加入中...
		</view>

		<view class="content message-padding" v-show="gameInfo.status == 2">
			Tips：上下左右打抱踢推
		</view>

		<view class="content message-padding" v-show="gameInfo.status == 3">
			已有{{gameInfo.nextPlayers ? gameInfo.nextPlayers.length : 0}}人报名，等待游戏开始...
		</view>

		<view class="select_ranks" v-if="gameInfo.gameNum.blue != 0">
			<image class="select_bg" src="../../static/bg_04.png"></image>

			<image class="number blue_num" :src="`../../static/number/img_${gameInfo.gameNum.blue}.png`"></image>
			<image class="number red_num" :src="`../../static/number/img_${gameInfo.gameNum.red}.png`"></image>

		</view>

		<view class="content role-select" v-if="gameInfo.gameNum.blue != 0 && !isCamp">
			<text class="title_text">选角色</text>
			<image class="role-select-line" src="../../static/bg_03.png"></image>
			<image class="select_bg select_role_bg" src="../../static/bg_02.png"></image>
			<view class="avatar" style="width: 90%; margin-top: 50rpx;">
				<image v-for="tr in roles" :class="{'select_role': role.id == tr.id, 'roleIsSelected': tr.isSelected}"
					:src="`https://qqr.aktioncorp.com${tr.url}`" @click="selectRole(tr)"></image>
			</view>

			<button class="videoBtn " @click="toJoin"><text>确 定</text></button>
		</view>


		<view class="progress-box" v-show="gameInfo.status == 2 && gameTime >= 5">

			<view>
				<text>生命值:</text><progress :percent="myState.health" activeColor="#e64340" show-info stroke-width="6" />
			</view>
			<view class="voicepad">
				<text>指令：</text>
				<ul>
					<li v-for="(item, index) in voiceState" :key="index">{{ item }}</li>
				</ul>
			</view>

			<button class="videoBtn " @touchstart="touchStart" @touchend="touchEnd">
				<text>{{ recordState?'松开 结束': '按住 说话'}}</text>
			</button>
			<view class="startYuyinImage" v-show="recordState">
				<cover-image src="/static/logo.png"></cover-image>
				<cover-view>正在识别...</cover-view>
			</view>
		</view>


	</view>
</template>

<script>
	import config from "../../utils/config.js"
	import apis from '../../utils/apis';
	const plugin = requirePlugin('WechatSI');
	const manager = plugin.getRecordRecognitionManager();

	const replaceMap = {
		'You': '右',
		'you': '右',
		'又': '右',
		'哟': '右',
		'有': '右',
		'钱': '前',
		'吼': '后',
		'Ho': '后',
		'ho': '后',
		'厚': '后',
		'腿': '推',
		'哒': '打',
		'爆': '抱',
		'暴': '抱',
		'报': '抱',
		'T': '踢',
		't': '踢',
		'sun': '上',
		'夏': '下',
		' ': '',
		'，': '',
		'。': '',
		// 添加其他要替换的键值对
	};


	export default {
		data() {
			return {
				timer: null,
				recordState: false, //说话状态
				voiceState: [],
				array: [], //N vs N
				index: 0,
				isCamp: false, //是否选择阵营
				eliminateNotice: false, //淘汰提示
				camp: undefined,
				role: undefined,
				roles: [],
				gameInfo: {
					roomId: 0,
					gameNum: {
						total: 0,
						blue: 0,
						red: 0,
					},
					blueUsers: [],
					redUsers: [],
					nextPlayers: []
				},
				userInfo: {},
				myState: {
					/** 血量 */
					health: 100
				},
				gameTime: 0
			}
		},
		onLoad() {
			console.log(this.$room);
			this.initRecord()
			this.gameInfo = this.$room;
			this.userInfo = this.$user;
			if (!this.gameInfo) {
				this.exitGame();
			}

			this.initGame();
		},
		onReady() {
			this.timer = setInterval(() => {
				this.getGameInfo();
			}, 1000);

			this.consumeAction();
		},
		destroyed() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
		},
		methods: {
			initGame() {
				//重置通知状态
				this.eliminateNotice = false;
				this.gameTime = 0;
				this.array = [];
				this.camp = undefined;
				this.role = undefined;
				this.isCamp = false;
				//如果未选择对战比例，初始化所有可能
				if (this.gameInfo.gameNum.blue == 0) {
					for (var i = 1; i <= this.gameInfo.gameNum.total / 2; i++) {
						this.array.push(i + ' vs ' + (this.gameInfo.gameNum.total - i));
					}
				}

				this.$api.roleList({}).then(res => {
					console.log(res);
					this.roles = res;
				}, err => {
					console.log(err);
				});
			},
			exitGame() {
				uni.showModal({
					title: '提示',
					content: '房间不存在或游戏已结束',
					showCancel: false,
					success: function(res) {
						if (res.confirm) {
							uni.exitMiniProgram({
								success: function() {
									console.log('退出小程序成功');
								},
								fail: function(err) {
									console.log('退出小程序失败', err);
								}
							})
						}
					}
				});
			},
			handleChange(e) {
				this.camp = parseInt(e.detail.value);
			},
			selectRole(roleObj) {
				if (roleObj.isSelected) {
					uni.showToast({
						title: '已被其他人选择',
						icon: 'error'
					})
					return;
				}
				this.role = roleObj;
			},
			toJoin() {
				if (this.camp === undefined) {
					uni.showToast({
						title: '请选阵营',
						icon: 'error'
					})
					return;
				}
				if (this.role === undefined) {
					uni.showToast({
						title: '请选角色',
						icon: 'error'
					})
					return;
				}
				var campStr = this.camp == 1 ? '蓝方' : '红方';
				var that = this;
				uni.showModal({
					title: '提示',
					content: '确认要选择' + campStr + '？',
					success: function(res) {
						if (res.confirm) {
							that.joinGame();
						} else {
							that.camp = undefined;
						}
					}
				});
			},
			bindPickerChange(e) {
				console.log(e);
				var vs = this.array[e.detail.value].split(' vs ');
				this.$api.gameUpate({
					roomId: this.gameInfo.roomId,
					redNum: parseInt(vs[0]),
					blueNum: parseInt(vs[1])
				}).then(res => {
					console.log(res);
				}, err => {
					console.log(err);
				});
			},
			//识别语音 -- 初始化
			initRecord() {
				const that = this;
				// 有新的识别内容返回，则会调用此事件
				manager.onRecognize = function(res) {
					console.log(res)
				}
				// 正常开始录音识别时会调用此事件
				manager.onStart = function(res) {
					console.log("成功开始录音识别", res)
				}
				// 识别错误事件
				manager.onError = function(res) {
					console.error("error msg", res)
				}
				//识别结束事件
				manager.onStop = function(res) {
					console.log('..............结束录音', res)
					console.log('录音临时文件地址 -->' + res.tempFilePath);
					console.log('录音总时长 -->' + res.duration + 'ms');
					console.log('文件大小 --> ' + res.fileSize + 'B');
					console.log('语音内容 --> ' + res.result);
					if (res.result == '') {
						return;
					}
					var result = res.result;
					for (let key in replaceMap) {
						result = result.replaceAll(key, replaceMap[key]);
					}
					console.log('转义后 --> ' + result);
					var operates = result.split('');
					for (var operate of operates) {
						that.checkOperate(operate);
					}
				}
			},
			onBtnUp() {
				this.userMove(1);
			},
			onBtnDown() {
				this.userMove(2);
			},
			onBtnLeft() {
				this.userMove(3);
			},
			onBtnRight() {
				this.userMove(4);
			},
			onBtnAttack() {
				this.userAction(1);
			},
			onBtnPush() {
				this.userAction(2);
			},
			onBtnCarry() {
				this.userAction(3);
			},
			onBtnKick() {
				this.userAction(4);
			},
			userAction(input) {
				this.$api.userAction({
					roomId: this.gameInfo.roomId,
					actionType: input,
					/** 微信信息 */
					wxUserInfo: this.userInfo
				})
			},
			userMove(input) {
				this.$api.userMove({
					roomId: this.gameInfo.roomId,
					moveDir: input,
					/** 微信信息 */
					wxUserInfo: this.userInfo
				})
			},
			userReady() {
				this.$api.userReady({
					roomId: this.gameInfo.roomId,
					type: 1,
					openId: this.userInfo.openId
				})
			},
			//语音  --按住说话
			touchStart(e) {
				this.recordState = true //录音状态;
				// 语音开始识别
				manager.start({
					lang: 'zh_CN', // 识别的语言，目前支持zh_CN en_US zh_HK sichuanhua
				})
			},
			//语音  --松开结束
			touchEnd(e) {
				// 语音结束识别
				manager.stop();
				this.recordState = false //录音状态;
			},
			//选择红蓝
			joinGame(tempCamp) {
				if(!this.role){
					// 先创建一个没有被选中的对象数组
					const availableRoles = this.roles.filter(t => !t.isSelected);
					// 生成一个随机索引
					const randomIndex = Math.floor(Math.random() * availableRoles.length);
					this.role = availableRoles[randomIndex];
				}
				//替换游戏角色头像
				this.userInfo.avatarUrl = config.baseUrl + this.role.url;
				this.$api.userJoin({
					roomId: this.gameInfo.roomId,
					teamType: tempCamp?tempCamp : this.camp,
					role: this.role.id,
					/** 微信信息 */
					wxUserInfo: this.userInfo
				}).then(res => {
					console.log(res);
					this.isCamp = true;
				}, err => {
					console.log(err);
				});
			},
			checkOperate(operate, doAction) {
				var coolingTime = 1000;
				var isVaild = true;
				switch (operate) {
					case '上':
						if (doAction) this.onBtnUp();
						break;
					case '下':
						if (doAction) this.onBtnDown();
						break;
					case '左':
						if (doAction) this.onBtnLeft();
						break;
					case '右':
						if (doAction) this.onBtnRight();
						break;
					case '打':
						if (doAction) this.onBtnAttack();
						break;
					case '推':
						coolingTime = coolingTime * 2;
						if (doAction) this.onBtnPush();
						break;
					case '抱':
						coolingTime = coolingTime * 2;
						if (doAction) this.onBtnCarry();
						break;
					case '踢':
						coolingTime = coolingTime * 2;
						if (doAction) this.onBtnKick();
						break;
					default:
						isVaild = false;
				}
				if (!doAction && isVaild) {
					this.voiceState.push(operate);
				}
				return coolingTime;
			},
			//消费动作
			consumeAction() {
				var coolingTime = 1000;
				var action = this.voiceState.shift();
				if (action) {
					coolingTime = this.checkOperate(action, true);
				}
				var that = this;
				setTimeout(function() {
					that.consumeAction();
				}, coolingTime);
			},
			continueGame(isFree) {
				var that = this;
				uni.showModal({
					title: '提示',
					content: isFree ? '恭喜胜利，是否免费玩下一局?' : '是否付费玩下一局?',
					success: function(res) {
						if (res.confirm) {
							//演示，暂时直接给加入
							that.userReady();
							if (isFree) {
								//this.userReady();
							} else {
								//显示二维码
							}
						} else {
							uni.exitMiniProgram({
								success: function() {
									console.log('退出小程序成功');
								},
								fail: function(err) {
									console.log('退出小程序失败', err);
								}
							})
						}
					}
				});
			},
			//获取游戏信息
			getGameInfo() {
				this.$api.gameInfo({
					roomId: this.gameInfo.roomId
				}).then(res => {
					console.log(res);
					if (res.isSucc) {
						this.gameInfo = res.res.roomInfo
						//234实际为2
						if (this.gameInfo.status == 3 || this.gameInfo.status == 4) {
							this.gameInfo.status = 2;
						} else if (this.gameInfo.status == 5) {
							this.gameInfo.status = 3;
						}

						//查看当前用户是否选择阵营
						for (var temp of this.gameInfo.playerState) {
							if (temp.userInfo.openId == this.userInfo.openId) {
								this.myState = temp;
								this.isCamp = true;
							} else {
								this.roles[temp.role - 1].isSelected = true;
								//如果选了还未提交，则清掉
								if (this.role && temp.role == this.role.id) {
									this.role = undefined;
								}
							}
						}
						//如果还没选，需要监控阵营剩余，如果没位置了自动选另外一队
						if (this.gameInfo.gameNum.red != 0 && !this.isCamp) {
							if ((this.gameInfo.gameNum.red - this.gameInfo.redUsers.length) == 0) {
								this.joinGame(1);
							} else if ((this.gameInfo.gameNum.blue - this.gameInfo.blueUsers.length) == 0) {
								this.joinGame(2);
							}
						}
						/** 游戏状态，1待开始，2进行中，3游戏结束 */
						switch (this.gameInfo.status) {
							case 1:
								if (this.gameTime > 0) {
									this.initGame();
								}
								break;
							case 2:
								this.gameTime++;
								//判断血量为0
								if (this.myState.health == 0 && !this.eliminateNotice) {
									this.eliminateNotice = true;
									this.continueGame();
									return;
								}
								break;
							case 3:
								//判断免费玩家提示
								if (!this.eliminateNotice) {
									this.eliminateNotice = true;
									var isFree = false;
									//查看当前用户是否选择阵营
									for (var temp of this.gameInfo.freePlayers) {
										if (temp == this.userInfo.openId) {
											isFree = true;
											break;
										}
									}

									this.continueGame(isFree);
									return;
								}
						}
					}
				}, err => {
					console.log(err);
				});
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.videoBtn {
		width: 80%;
		position: absolute;
		border-radius: 35px;
		bottom: 50rpx;
		background: #226be4;
	}

	.videoBtn text {
		color: #fff;
	}

	.videoBtnBg {
		background: #bdb4b4;
	}

	.startYuyinImage {
		display: flex;
		justify-content: center;
		flex-flow: column;
		position: fixed;
		bottom: 250rpx;
		left: 50%;
		width: 240rpx;
		height: 300rpx;
		background: rgba(0, 0, 0, 0.6);
		border-radius: 20rpx;
		color: #fff;
		text-align: center;
		margin-left: -120rpx;
	}

	.startYuyinImage cover-image {
		margin: 0 auto;
		width: 65rpx;
		height: 102rpx;
	}

	.startYuyinImage cover-view {
		margin-top: 25rpx;
	}

	.uni-picker-tips {
		font-size: 12px;
		color: #666;
		margin-bottom: 15px;
		padding: 0 15px;
		/* text-align: right; */
	}

	.progress-box {
		padding: 60rpx;
	}

	.voicepad ul {
		list-style: none;
		margin-left: 10rpx;
	}

	.voicepad li {
		display: inline;
	}

	.camp-select {
		padding-bottom: 170px;
		padding-top: 30px;
	}

	.message-padding {
		padding-top: 130rpx;
		padding-bottom: 210px;
	}

	.camp-select radio {
		padding-left: 20rpx;
		padding-top: 20rpx;
	}

	view {
		margin-top: 20rpx;
	}

	.title_bg {
		position: absolute;
		margin-top: 386rpx;
		z-index: -1;
	}

	.title_text {
		color: #2fcef9;
	}

	.select_ranks {
		justify-content: center;
		align-items: center;
		display: flex;
		margin-bottom: 100px;
	}

	.select_bg {
		position: absolute;
		z-index: -1;
	}

	.select_role_bg {
		margin-top: 50px;
		width: 95%;
		height: 150px;
	}

	.select_ranks .number {
		width: 59px;
		height: 50px;
		display: inline-block;
	}

	.blue_num {
		margin-left: 0%;
	}

	.red_num {
		margin-left: 30%;
	}

	.role-select-line {
		width: 211px;
		height: 3px;
	}

	.avatar image {
		/* 其他的样式... */
		width: 90rpx;
		height: 90rpx;
		border-radius: 50%;
		overflow: hidden;
		border: 3px solid #ccc;
		margin-left: 10rpx;
	}

	.avatar .select_role {
		border: 3px solid #2fcef9;
		/* 添加动画 */
		animation: flow 3s infinite linear;
	}

	.avatar .roleIsSelected {
		border: 3px solid #ff0000;
	}

	@keyframes flow {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}
</style>